<template>
  <el-dialog
    :title="modalType"
    :model-value="modelValue"
    width="1000"
    destroy-on-close
    @open="getDetail"
    @close="handleCancel"
  >
    <el-form
      :model="formData"
      label-width="100px"
      ref="formRef"
      :rules="formRules"
    >
      <el-row>
        <el-col :span="20" :offset="2">
          <el-form-item label="领导姓名" prop="userId">
            <el-select
              placeholder="请输入领导姓名"
              v-model="formData.userId"
              multiple
              @click="activeModal"
              ref="leaderRef"
              class="w-70%"
              @remove-tag="removeTag"
              :disabled="isDisabled"
            >
              <el-option
                v-for="item in leaderList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="10" :offset="2">
          <el-form-item label="到访单位" prop="deptId">
            <el-select
              placeholder="请选择到访单位"
              v-model="formData.deptId"
              @change="changeDept"
              clearable
              :disabled="isDisabled"
            >
              <el-option
                v-for="item in deptList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="到访网点" prop="outletList">
            <el-select
              placeholder="请选择到访网点"
              v-model="formData.outletList"
              @click="activeOutlet"
              ref="outletRef"
              multiple
              clearable
              :disabled="isDisabled"
              class="w-full"
            >
              <el-option
                v-for="item in branchList"
                :key="item"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="10" :offset="2">
          <el-form-item label="到访人数" prop="visitNum">
            <el-input
              placeholder="请输入到访人数"
              v-model="formData.visitNum"
              style="width: 200px"
              clearable
              :disabled="isDisabled"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="10">
          <el-form-item label="到访日期" prop="visitTimeBegin">
            <el-date-picker
              v-model="timeArray"
              type="daterange"
              range-separator="至"
              start-placeholder="到访日期起"
              end-placeholder="到访日期止"
              value-format="YYYY-MM-DD"
              style="width: 100%"
              clearable
              @change="changeTime"
              :disabled="isDisabled"
              class="w-full"
            />
          </el-form-item>
        </el-col>

        <el-col :span="20" :offset="2">
          <el-form-item label="附件" prop="fileNames">
            <el-upload
              class="upload-demo"
              action="#"
              :http-request="handleFileChange"
              :accept="uploadType.toString()"
              :show-file-list="false"
              :multiple="true"
              :disabled="isDisabled"
            >
              <el-button
                :disabled="isDisabled"
                type="primary"
                style="font-size: 14px"
                ><el-icon> <UploadFilled /> </el-icon>上传文件</el-button
              >
              <template #tip>
                <div class="el-upload__tip float-right ml-5px">
                  支持格式：{{ uploadType.toString() }}，单个文件不能超过20MB
                </div>
              </template>
            </el-upload>
            <div class="text-14px mt-10px" style="width: 100%">
              <div v-for="(item, index) in fileList" :key="item.fileId">
                <a style="color: #409eff" :href="item.url">{{
                  item.origFileName
                }}</a>
                <el-button
                  text
                  plain
                  @click="delFileName(index)"
                  v-if="!isDisabled"
                  >删除</el-button
                >
              </div>
            </div>
          </el-form-item>
        </el-col>

        <el-col :span="20" :offset="2">
          <el-form-item label="备注信息" prop="remark">
            <el-input
              type="textarea"
              v-model="formData.remark"
              placeholder="备注信息"
              :rows="4"
              maxlength="200"
              show-word-limit
              :disabled="isDisabled"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer" v-if="modalType !== '查看详情'">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
      <div class="dialog-footer" v-else>
        <el-button @click="handleCancel">关 闭</el-button>
      </div>
    </template>
    <SelectDialog
      :dialog-param="dialogEvent"
      @ok="selectPerson"
      @close="dialogEvent.isDialog = false"
    />
  </el-dialog>
</template>

<script setup>
import { uploadFile, delFile } from '@/api/salesManage/contractManage'
import { outlet_type } from '@/hooks/dict/business'
import useCommonStore from '@/store/modules/common'
import { updateUnitList, getUnitListByPage } from '@/api/toGrassrootsUnit'
import { useDict } from '@/utils/dict'
const { bidding_unit } = useDict('bidding_unit')

const deptList = computed(() => {
  const array = bidding_unit.value.map(v => v)
  array.splice(0, 1)
  return array
})
const commonStore = useCommonStore()
const { proxy } = getCurrentInstance()
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  modalType: {
    type: String,
    default: '新增'
  },

  formId: {
    type: String || Number,
    default: ''
  }
})

const emit = defineEmits(['update:modelValue', 'refresh'])

const dialogEvent = ref({
  nodeKey: 'uuid',
  isDialog: false,
  data: [],
  multiple: true,
  defaultCheckedKeys: [],
  checkStrictly: false,
  title: '人员选择'
})

const isDisabled = ref(false)
function getDetail() {
  if (props.formId && props.modalType !== '新增') {
    getUnitListByPage({ formId: props.formId }).then(res => {
      formData.value = res.data
      // 设置到访单位
      formData.value.deptId = formData.value.deptId || null
      // 设置到访网点
      formData.value.outletList = formData.value.outletList.map(v => v.outlet)
      if (formData.value.deptId) {
        branchList.value = outlet_type.value
          .find(v => v.value == formData.value.deptId)
          .remark.split('、')
      }

      // 设置到访日期
      timeArray.value = [res.data.visitTimeBegin, res.data.visitTimeEnd]
      // 设置领导姓名
      dialogEvent.value.defaultCheckedKeys = res.data.userNameList.map(
        v => 'U' + v.userId
      )
      formData.value.userId = res.data.userNameList.map(v => v.userId)
      leaderList.value = res.data.userNameList.map(v => ({
        value: v.userId,
        label: v.nickName
      }))

      // 附件
      formData.value.fileNames = res.data.sysAttachFiles.map(v => v.fileName)
      fileList.value = (res.data.sysAttachFiles || []).map(v => v)
    })
  } else {
    formData.value = {}
    fileList.value = []
    timeArray.value = []
  }

  if (props.modalType === '查看详情') {
    isDisabled.value = true
  } else {
    isDisabled.value = false
  }
  init()
}

async function init() {
  const res = await commonStore.getUseTreeData()
  dialogEvent.value.data = [res[0]]
}

const formData = ref({})
const formRules = ref({
  deptId: [{ required: true, message: '请选择到访单位', trigger: 'blur' }],
  outlet: [{ required: true, message: '请选择网点', trigger: 'blur' }],
  userId: [{ required: true, message: '请选择人员', trigger: 'blur' }],
  // fileNames: [{ required: true, message: '请上传附件', trigger: 'blur' }],
  visitNum: [
    { required: true, message: '请填写到访人数', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value && !/^[1-9]\d{0,}$/.test(value.toString())) {
          callback(new Error('请输入正整数'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  outletList: [{ required: true, message: '请选择到访网点', trigger: 'blur' }],
  visitTimeBegin: [
    { required: true, message: '请选择到访时间', trigger: 'blur' }
  ]
})
const timeArray = ref()
const leaderList = ref([])

// 选择人员
function activeModal() {
  dialogEvent.value.isDialog = true
  proxy.$nextTick(() => {
    proxy.$refs.leaderRef.blur()
  })
}

// 删除标签
function removeTag(tagVal) {
  formData.value.userId = dialogEvent.value.defaultCheckedKeys.map(v =>
    v.replace(/U/g, '')
  )
  dialogEvent.value.isDialog = true
}

/**
 * @params 接受SelectDialog组件返回参数
 */
function selectPerson(val) {
  // sales.value = val.labelData.join(',')
  dialogEvent.value.isDialog = false
  dialogEvent.value.defaultCheckedKeys = val.defaultCheckedKeys
  formData.value.userId = val.defaultCheckedKeys.map(v => v.replace(/U/g, ''))
  leaderList.value = val.selectData.map(v => ({
    value: v.id.toString(),
    label: v.label
  }))
  formData.value.userNameList = val.selectData.map(v => ({
    userId: v.id,
    userName: v.userName,
    nickName: v.label,
    deptId: v.deptId
  }))

  console.log(formData.value.leaderList, branchList.value, '122222')
}

// 选择到访单位
function changeDept(val) {
  formData.value.outletList = null
  if (val) {
    const deptName = deptList.value.find(v => v.value === val)
    branchList.value = outlet_type.value
      .find(v => v.value == deptName.value)
      .remark.split('、')
  } else {
    branchList.value = []
  }
}

// 选择网点
function activeOutlet() {
  if (!formData.value.deptId) {
    proxy.$modal.msgWarning('请先选择到访单位')
    proxy.$nextTick(() => {
      proxy.$refs.outletRef.blur()
    })
    return
  }
}

// 选择到访时间
function changeTime(val) {
  if (val) {
    formData.value.visitTimeBegin = val[0]
    formData.value.visitTimeEnd = val[1]
  } else {
    formData.value.visitTimeBegin = null
    formData.value.visitTimeEnd = null
  }
}

const uploadType = [
  '.rar',
  '.zip',
  '.doc',
  '.docx',
  '.pdf',
  '.xls',
  '.xlsx',
  '.jpg',
  '.png',
  '.gif'
]
const branchList = ref([])
// 上传附件
const fileList = ref([])
async function handleFileChange(params) {
  let form = new FormData()
  form.append('file', params.file)
  if (params.file.size / 1024 / 1024 > 20) {
    proxy.$modal.msgError('单个文件不能超过20MB!')
    return false
  }
  const fileName = params.file.name.split('.')
  const fileExt = fileName[fileName.length - 1]
  const isTypeOk = uploadType.toString().includes(fileExt)
  console.log('fileExt==>', fileExt)
  console.log('isTypeOk==>', isTypeOk)

  if (!isTypeOk) {
    proxy.$modal.msgError('文件格式不正确, 请上传正确格式的文件!')
    return false
  }

  try {
    const res = await uploadFile(form)
    if (res.code === 200 && res.data) {
      if (!formData.value.fileNames) {
        formData.value.fileNames = []
      }
      formData.value.fileNames.push(res.data.fileName)
      fileList.value.push(res.data)
    } else {
      console.log(res.msg)
    }
  } catch (error) {
    console.error(error)
  }
}

const deleteImgArray = ref([])
async function delFileName(index) {
  proxy.$modal.confirm('是否删除该文件').then(async () => {
    const file = fileList.value[index]
    formData.value.fileNames.splice(index, 1)
    fileList.value.splice(index, 1)
    proxy.$modal.msgSuccess('删除成功')
    deleteImgArray.value.push(file.fileName)
  })
}

function delFileRequest() {
  if (!deleteImgArray.value.length) return
  for (let i = 0; i < deleteImgArray.value.length; i++) {
    if (deleteImgArray.value.length) {
      delFile(deleteImgArray.value.splice(0, 1))
    }
  }
}

function handleCancel() {
  emit('update:modelValue', false)
  // proxy.$refs.formRef.resetFields()
  formData.value = {}
  fileList.value = []
  timeArray.value = []
  delFileRequest()
}

function handleSubmit() {
  proxy.$refs.formRef.validate(async valid => {
    if (!valid) return

    const params = { ...formData.value }
    params.outletList = params.outletList.map(v => ({ outlet: v }))
    params.deptName = deptList.value.find(v => v.value == params.deptId).label
    console.log(params.deptId, deptList.value)
    // if (params.fileNames && Array.isArray(params.fileNames)) {
    //   params.fileNames = params.fileNames.join(',')
    // }
    if (props.modalType === 'add') {
      updateUnitList(params).then(() => {
        proxy.$modal.msgSuccess('新增成功')
        handleCancel()
        emit('refresh')
      })
    } else {
      params.formId = props.formId
      updateUnitList(params).then(() => {
        proxy.$modal.msgSuccess('修改成功')
        handleCancel()
        emit('refresh')
      })
    }
  })
}
</script>

<style scoped lang="scss">
::v-deep textarea {
  resize: none;
}
</style>
